package com.yf.notify.modules.sms.providers.aliyun.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.yf.ability.config.dto.CfgPropDTO;
import com.yf.ability.config.enums.ConfigType;
import com.yf.ability.config.enums.ProviderType;
import com.yf.ability.config.service.CfgPropService;
import com.yf.base.api.exception.ServiceException;
import com.yf.notify.modules.sms.providers.aliyun.config.AliyunSmsConfig;
import com.yf.notify.modules.sms.service.SmsService;
import com.yf.notify.utils.ArrayUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;

@Log4j2
@Service("aliyunSmsService")
public class AliyunSmsServiceImpl implements SmsService {

    @Autowired
    private CfgPropService cfgPropService;


    /**
     * 发送成功代码
     */
    private static final String SUCCESS_CODE = "OK";
    /**
     * 最大发送量
     */
    private static final int MAX_TO = 1000;


    @Override
    public boolean sendSms(String templateId, String [] mobiles, LinkedHashMap<String,String> params) throws ServiceException{

        CfgPropDTO dto = cfgPropService.detail(ConfigType.SMS, ProviderType.ALIYUN);
        AliyunSmsConfig conf = JSON.parseObject(dto.getData(), AliyunSmsConfig.class);

        if(conf == null || StringUtils.isBlank(conf.getAccessKeyId()) || StringUtils.isBlank(conf.getAccessKeySecret())){
            throw new ServiceException("短信配置错误，请联系管理员！");
        }

        // 最多1000个
        if(mobiles.length > MAX_TO){
            List<List<String>> list = ArrayUtils.split(mobiles, MAX_TO);
            boolean result = true;
            for(List<String> item: list){
                String [] subs = item.toArray(new String[0]);
                result = sendSms(conf, templateId, subs, params);
                // 出错不发
                if(!result){
                    break;
                }
            }
            return result;
        }else{
            // 直接发送
            return sendSms(conf, templateId, mobiles, params);
        }
    }


    /**
     * 发送短信
     * @param conf
     * @param templateId
     * @param mobiles
     * @param params
     * @return
     * @throws ServiceException
     */
    private boolean sendSms(AliyunSmsConfig conf, String templateId, String [] mobiles, LinkedHashMap<String,String> params) throws ServiceException{

        Config config = new Config()
                .setAccessKeyId(conf.getAccessKeyId())
                .setAccessKeySecret(conf.getAccessKeySecret());
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        Client client;
        try {
            client = new Client(config);
            SendSmsRequest request = new SendSmsRequest();
            // 逗号隔开的字符串
            request.setPhoneNumbers(StringUtils.join(mobiles, ","));
            request.setSignName(conf.getSign());
            request.setTemplateCode(templateId);
            request.setTemplateParam(JSON.toJSONString(params));
            SendSmsResponse response = client.sendSms(request);
            String code = response.body.code;

            // 响应码
            if(SUCCESS_CODE.equalsIgnoreCase(code)) {
                return true;
            }
            throw new ServiceException(response.body.message);

        } catch (Exception e) {
            log.error(e);
            throw new ServiceException(e.getMessage());
        }
    }
}
